import pygame,sys,func,time
from setting import Setting
from square import Square
from wall import Wall
from font import *
import os

def main():
	pygame.init()
	s = Setting()
	win = pygame.display.set_mode(s.win)

	square = Square(win,s)
	walls = []

	play = Play(win,s)
	game_over = GameOver(win,s)
	ranking_list = RankingList(win,s)
	play_again = PlayAgain(win,s)
	back = Back(win,s)

	pygame.display.set_caption('像素方块')
	fclock = pygame.time.Clock()

	while True:
		win.fill(s.win_color)
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == pygame.KEYDOWN:
				if event.key == pygame.K_SPACE:
					square.space = True
			elif event.type == pygame.KEYUP:
				if event.key == pygame.K_SPACE:
					square.space = False
			elif event.type == pygame.MOUSEBUTTONDOWN:
				pos_x,pos_y = pygame.mouse.get_pos()
				if s.game == False and s.over == False:
					if play.rect.left<pos_x<play.rect.right and\
						play.rect.top<pos_y<play.rect.bottom:
						s.game = True
						square.play = True
					elif ranking_list.rect.left<pos_x<\
						ranking_list.rect.right and\
						ranking_list.rect.top<pos_y<\
						ranking_list.rect.bottom:
						s.rank = True
						os.popen('call_ui.py')
				elif s.over == False and s.game == True:
					square.space = True
				elif s.over == True and s.game == True:
					if play_again.rect.left<pos_x<\
						play_again.rect.right and\
					   play_again.rect.top<pos_y<\
					    play_again.rect.bottom:
					    s.over = False
					    square = Square(win,s)
					    walls = []
					    square.play = True
					if back.rect.left<pos_x<back.rect.right and\
						back.rect.top<pos_y<back.rect.bottom:
						s.over = False
						s.game = False
						square = Square(win,s)
						walls = []

		if s.over == False and s.game == True:#游戏中
			func.add_wall(walls,win,s)
			func.update(walls,square)
			func.check_crash(walls,square,s)
			func.plus(walls,square,s)
			fclock.tick(s.fps)
		elif s.over == False and s.game == False:#开始
			play.update()
			ranking_list.update()
			square.update()
		elif s.over == True and s.game == True:#gameover
			func.update(walls,square,True)
			back.update()
			game_over.update()
			play_again.update()
			s.score = 0
		pygame.display.update()

if __name__ == '__main__':
	main()